package cn.edu.sgu.www.mhxysy.service.except.impl;

import cn.edu.sgu.www.mhxysy.vo.Imager;
import cn.edu.sgu.www.mhxysy.config.property.UploadsProperties;
import cn.edu.sgu.www.mhxysy.mapper.except.ImageRenameMapper;
import cn.edu.sgu.www.mhxysy.service.except.ImageRenameService;
import cn.edu.sgu.www.mhxysy.util.StringUtils;
import cn.edu.sgu.www.mhxysy.util.UploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Service
public class ImageRenameServiceImpl implements ImageRenameService {

    private final UploadsProperties uploadsProperties;
    private final ImageRenameMapper imageRenameMapper;

    @Autowired
    public ImageRenameServiceImpl(UploadsProperties uploadsProperties, ImageRenameMapper imageRenameMapper) {
        this.uploadsProperties = uploadsProperties;
        this.imageRenameMapper = imageRenameMapper;
    }

    @Override
    public void rename(String tableName, String imageField) {
        String path = null;
        // 驼峰命名转为下划线命名
        String table = StringUtils.toLower(tableName);

        // 批量修改图片名和表的image字段值
        List<Imager> list = imageRenameMapper.selectByTableName(table, imageField);
        int base = UploadUtils.getBase(table.charAt(0));

        for (Imager imager : list) {
            String image = imager.getImage();

            if (StringUtils.isNotEmpty(image)) {
                // 删除图片后缀：?timestamp=
                int index = image.indexOf("?");

                if (index > 0) {
                    image = image.substring(0, index);
                }

                if (path == null) {
                    path = image.substring(0, image.lastIndexOf("/") + 1);
                }

                int id = Integer.parseInt(imager.getId());
                // 新文件名
                String name = path + (id + base) + image.substring(image.lastIndexOf('.'));

                imageRenameMapper.updateImageById(id, name, table, imageField);

                String from = uploadsProperties.getPath() + image;
                String to = uploadsProperties.getPath() + name;

                File origin = new File(from);
                File target = new File(to);

                boolean result = origin.renameTo(target);

                if (!result) {
                    log.debug("重命名失败：{} => {}", origin.getName(), target.getName());
                }
            }
        }
    }

}